package com.example.base.app;

import com.example.base.plugin.AppPlugin;
import com.example.base.utils.ReflectUtils;
import com.example.base.websocket.AppWebSocket;
import com.example.base.websocket.interceptor.WebSockerMethodInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AppHandlerLoad {

    @Autowired
    AppHandlerServer appHandlerServer;

    @Autowired
    private AppClassService appClassService;

    @Autowired
    private ThreadPoolTaskExecutor asyncServiceExecutor;

    public void load(String appName){
        asyncServiceExecutor.execute(()->{
            log.info("开始加载 appName {} 的拦截器",appName);
            List<Class<?>> classList=appClassService.getClassByAppName(appName);
            for(Class<?> cls:classList){
                if(ReflectUtils.isClassImplementedInterface(cls, AppHandler.class)){
                    Enhancer enhancer = new Enhancer();
                    enhancer.setSuperclass(cls);
                    enhancer.setCallback(new AppHandlerMethodInterceptor(appName,cls));
                    AppHandler appHandler = (AppHandler) enhancer.create();
                    appHandlerServer.addAppHandler(appName,appHandler);
                }
            }
        });
    }

}
